import {Component, Inject, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {AuthService} from "@shared/service/auth/auth.service";
import {ParentService} from "@train/parent/parent.service";
import {
  ClassForStudentVO, SNSResult, StudentTestLastScoreVO, StudentTestScoreRadarChartVO,
  TrainStudent
} from "@interface/index";
import {ImageServeService} from "@shared/service/image/image-serve.service";
import {SCRIPT_LOADER, ScriptLoader} from "@core/script-loader/script-loader";

const ABILITY_CHART_OPTIONS = (param) => {
  return {
    radar: [
      {
        indicator: param.nameArray,
        center: ['50%', '50%'],
        radius: 67, //半径，可放大放小雷达图
        name: { //外围文字描述
          textStyle: {
            color: '#000000',
            fontSize: 15
          },
          // formatter: function (v, e) {
          //   return '<span style="color:red;">'+v+'</span>'
          // },
        },
        nameGap: 15, //外围文字距离雷达图距离
        splitArea: {//层级间隔区域
          show: false
        },
        axisLine: {//半径散射线
          lineStyle: {
            color: '#c1c1c1'
          }
        }
      }
    ],
    series: [
      {
        type: 'radar',
        itemStyle: {
          normal: {
            areaStyle: {}
          }
        },
        data: [
          {
            value: param['scoreArray'],
            symbol: 'none', //节点圆圈不显示
            itemStyle: {
              normal: {
                color: '#f4d320',
                label: {
                  show: true,
                  formatter: function (params) {
                    return params.value;
                  }
                },
                lineStyle: {
                  color: "#f4d320",
                  width: 2
                }
              }
            },
            areaStyle: {
              normal: {
                opacity: 0.56
              }
            }
          },
          {
            value: param['minArray'],
            symbol: 'none',
            itemStyle: {
              normal: {
                color: '#b71c25',
                label: {
                  show: true,
                  formatter: function (params) {
                    return params.value;
                  }
                },
                lineStyle: {
                  color: "#b71c25",
                  width: 2
                }
              }
            },
            areaStyle: {
              normal: {
                opacity: 0.5
              }
            }
          }
        ]
      }
    ]
  };
};

@Component({
  selector: 'seed-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class TrainParentComponent implements OnInit {
  public authOrgId: string;
  public curStudent: TrainStudent;
  public curClass: ClassForStudentVO;
  public classes: ClassForStudentVO[] = [];
  public childList: TrainStudent[] = [];
  public content: any;
  public defaultIcon;
  @ViewChild('childRenList') childRenList;
  @ViewChild('classList') classList;
  @ViewChild('tipsContent') tipsContent;
  public stateArr = ['未开课', '上课中', '已上完'];
  public stateObj = {
    '-1': '暂未分班',
    0: '未开课',
    1: '上课中',
    2: '已上完'
  };
  public randarOptionObj = {
    nameArray: [],
    minArray: [],
    scoreArray: [],
    splitNumber: 5
  };
  public unReadCount = 0; // 未读数
  public showChart: boolean = false;
  public options: Object;
  public echartsIntance: any;
  public eCharts: any;
  public studentScore: StudentTestLastScoreVO;
  public latestDate: string;
  public dataStore = {
    idType: '', // 身份类型
    studentId: 0
  };

  constructor(
    private activatedRoute: ActivatedRoute,
    private authService: AuthService,
    private parentService: ParentService,
    private imageServe: ImageServeService,
    private router: Router,
    @Inject(SCRIPT_LOADER) public scriptLoader: ScriptLoader
  ) {
    this.eCharts = this.scriptLoader.load('echarts');
    this.defaultIcon = this.imageServe.getUserIcon();
    activatedRoute.queryParams.subscribe(param => {
      this.authOrgId = param['authOrgId'];
      this.dataStore.idType = param['idType'];
      this.dataStore.studentId = param['studentId'];
    });
    authService.setAuthOrgId(this.authOrgId);
    this.findStudent(this.authOrgId);
  }

  showECharts() {
    this.options = ABILITY_CHART_OPTIONS(this.randarOptionObj);
  }

  getIcon(name: string): string {
    return this.imageServe.getIcon(name);
  }

  /**
   * @author guoqs1331
   * @time 2018/4/13
   * @description
   */
  showTips() {
    this.tipsContent.show();
  }

  /**
   * @author guoqs1331
   * @time 2018/4/13
   * @description
   */
  closeTips() {
    this.tipsContent.hide();
  }

  /**
   * @author guoqs1331
   * @time 2018/1/26
   * @description
   */
  findClassRoomByStudId(studentId: string) {
    this.parentService.findClassRoomByStudId(studentId).subscribe(res => {
      res.data && (this.classes = res.data);
      this.curClass = this.classes[0];
      this.findUnreadCount();
    });
  }

  /**
   * @author guoqs1331
   * @time 2018/2/28
   * @description 查询可是点评未读数
   */
  findUnreadCount() {
    const studentId = this.curStudent.id,
      classId = this.curClass.classRoomId;
    this.parentService.findUnreadCount(studentId, classId).subscribe(res => {
      res.data && (this.unReadCount = res.data);
    })
  }

  /**
   * @author guoqs1331
   * @time 2018/2/27
   * @description 切换班级
   */
  switchClass(): void {
    this.classList.show();
  }

  /**
   * @author guoqs1331
   * @time 2018/2/27
   * @description 隐藏班级modal
   */
  hideClassModal(): void {
    this.classList.hide();
  }

  /**
   * @author guoqs1331
   * @time 2018/1/29
   * @description 切换孩子
   */
  switchChild(): void {
    this.childRenList.show();
  }

  /**
   * @author guoqs1331
   * @time 2018/2/1
   * @description 隐藏模态框
   */
  hidenModal(): void {
    this.childRenList.hide();
  }

  /**
   * @author guoqs1331
   * @time 2018/1/29
   * @description
   */
  chooseChild(item: TrainStudent): void {
    this.curStudent = item;
    this.getLastScore(); //查询最后一次成绩
    this.requestEChartInfo(); //请求当前学生echart信息
    this.findClassRoomByStudId(item.id + '');
  }

  /**
   * @author guoqs1331
   * @time 2018/3/2
   * @description
   */
  chooseClass(item: ClassForStudentVO): void {
    this.curClass = item;
  }

  /**
   * @author guoqs1331
   * @time 2018/1/29
   * @description 获取默认图片
   */
  get noDataDefaultImg(): string {
    return this.imageServe.getDefaultGraph('noData');
  }

  /**
   * @author guoqs1331
   * @time 2018/1/29
   * @description 查看班级详情
   */
  checkClassDetail(item: ClassForStudentVO) {
    this.router.navigate([`/train/parent/class-remark/${item.classRoomId}/${this.curStudent.id}`], {
      queryParams: {
        className: item.className,
        courseType: item.courseType
      }
    });
  }

  /**
   * @author guoqs1331
   * @time 2018/1/29
   * @description 跳转孩子页面
   */
  goChildPage() {
    this.router.navigate([`/train/parent/student/${this.curStudent.id}`]);
    // this.router.navigate([`/train/parent/child-option/${this.curStudent.id}`], {queryParams: {studentName: this.curStudent.name}});
  }

  /**
   * @author ouxh862
   * @time 2018/3/1
   * @description 跳转课程表
   */
  goSchedule() {
    this.router.navigate([`/train/parent/schedule/${this.curStudent.id}`]);
  }

  goToGrowUpPage() {
    const studentId = this.curStudent.id + '';
    this.router.navigate([`/train/parent/grow-up-list/${studentId}`], {queryParams: {studentName: this.curStudent.name}});
  }

  onChartInit(e) {
    this.echartsIntance = e;
  }

  /**
   * @author guoqs1331
   * @time 2018/4/12
   * @description 获取学习成绩七星雷达图
   */
  studentScoreRadarChart(): Promise<SNSResult<StudentTestScoreRadarChartVO>> {
    const curStudentId = this.curStudent.id;
    return this.parentService.studentScoreRadarChart(curStudentId).toPromise();
  }

  /**
   * @author guoqs1331
   * @time 2018/4/15
   * @description 最后一次测试成绩
   */
  getLastScore() {
    this.parentService.getLastScore(this.curStudent.id).subscribe(res => {
      if (!res.data) {
        this.studentScore = null;
        return;
      }
      this.studentScore = res.data;
    });
  }


  /**
   * @author guoqs1331
   * @time 2018/1/26
   * @description
   */
  async findStudent(orgUserId: string) {
    if (this.dataStore.idType === 'teacher') {   // 教练端
      const params = {
        studentId: this.dataStore.studentId,
        orgUserId: this.authService.getAuthOrgId(),
      };
      const result = await this.parentService.findStudentInfo(params).toPromise();
      this.curStudent = result.data;
      // subscribe(res => {
      //   if (res.result === '0' && res.data) {
      //     this.curStudent = res.data;
      //   }
      // });
    } else {
      const result = await this.parentService.findSutdent(orgUserId).toPromise();
      const students = result.data;
      if (students) {
        this.curStudent = students[0];
        this.childList = [...students];
      }
    }
    this.getLastScore(); // 查询最后一次成绩
    this.findClassRoomByStudId(this.curStudent.id + '');
    this.requestEChartInfo();
  }

  /**
   * @author guoqs1331
   * @time 2018/4/12
   * @description 加载渲染echart
   */
  requestEChartInfo(): void {
    const radarInfo = this.studentScoreRadarChart();
    Promise.all([this.eCharts, radarInfo]).then((resArray) => {
      if (resArray['1']['data']) {
        this.displayECharts(resArray['1']['data']);
      }
    });
  }

  /**
   * @author guoqs1331
   * @time 2018/4/15
   * @description
   */
  displayECharts(obj) {
    const radarMapObj = obj;
    if (radarMapObj['testModels'] && radarMapObj['testModels'].length > 0) {
      const testModels = radarMapObj['testModels'];
      this.latestDate = radarMapObj['latestDate'];
      let nameArray = [], scoreArray = [], minArray = [];
      testModels.forEach(item => {
        nameArray.push({
          'name': item['modeName'] + '\n' + item['totalAbilityScore'],
          max: radarMapObj['maxValue'],
          nameTextStyle: {
            align: 'center',
            width: 500
          }
        });
        minArray.push(radarMapObj['minValue'])
      });
      testModels.forEach(item => {
        scoreArray.push(item['totalAbilityScore'])
      });
      this.randarOptionObj = {
        nameArray: nameArray,
        minArray: minArray,
        scoreArray: scoreArray,
        splitNumber: 5
      };
      this.showChart = true;
      this.showECharts();
    }
  }

  ngOnInit() {
  }

}
